package com.taokatao.cardmee.business.carddetail;

import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.rd.PageIndicatorView;
import com.taokatao.cardmee.App;
import com.taokatao.cardmee.BaseActivity;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.R;
import com.taokatao.cardmee.api.ApiManager;
import com.taokatao.cardmee.api.RespWrapper;
import com.taokatao.cardmee.api.SubscriberAdapter;
import com.taokatao.cardmee.api.model.CardFDInfo;
import com.taokatao.cardmee.db.model.Card;
import com.taokatao.cardmee.util.PtrHeaderHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * 商家分店对应的界面
 */
public class CardFDActivity extends BaseActivity {

    @BindView(R.id.l_empty) View lEmpty;
    @BindView(R.id.pageIndicatorView) PageIndicatorView vPageIndicator;
    @BindView(R.id.l_ptr_frame) PtrFrameLayout lPtrFrame;
    @BindView(R.id.v_pager) ViewPager vPager;
    CourseInfoAdapter pagerAdapter;
    @BindView(R.id.v_recycler) RecyclerView vRecycler;
    RecordAdapter recordAdapter;

    Card c;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSupportTouchBack = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_fd);
        ButterKnife.bind(this);

        c = (Card) getIntent().getSerializableExtra("extra_card");

        vPager.setAdapter(pagerAdapter = new CourseInfoAdapter());
        vPageIndicator.setVisibility(View.GONE);
        vPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        lPtrFrame.setEnabled(false);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        lPtrFrame.setEnabled(true);
                        break;
                }
                return false;
            }
        });

        vRecycler.setHasFixedSize(true);
        vRecycler.setLayoutManager(new LinearLayoutManager(this));
        vRecycler.setAdapter(recordAdapter = new RecordAdapter());

        PtrHeaderHelper.initMaterial(this, lPtrFrame);

        lPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, vRecycler, header);
            }

            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                requestGetMcardProductDetails();
            }
        });

        requestGetMcardProductDetails();
    }


    private void requestGetMcardProductDetails() {
        ApiManager.i().getMcardProductDetails(this, App.i().getCurrUser().getUuid(),
                c.getMCardId(), c.getBusinessId(), c.getSid(), c.getIsMyCard(), new SubscriberAdapter<RespWrapper<CardFDInfo>>() {
                    @Override
                    public void onNext(RespWrapper<CardFDInfo> o) {
                        super.onNext(o);
                        if (o.code == C.http.RESULT_CODE_SUCCESS) {
                            CardFDInfo cardFDInfo = o.decode(CardFDInfo.class);
                            pagerAdapter.set(cardFDInfo);
                            vPageIndicator.setVisibility(View.VISIBLE);
                            vPageIndicator.setViewPager(vPager);

                            recordAdapter.set(cardFDInfo);

                            boolean emptyRecord = !(cardFDInfo.orderFinanceList != null && cardFDInfo.orderFinanceList.size() > 0);
                            lEmpty.setVisibility(emptyRecord ? View.VISIBLE : View.GONE);
                        }
                    }
                }.pullToRefresh(lPtrFrame));
    }

    static class CourseInfoAdapter extends PagerAdapter {
        CardFDBaseInfoLayout lBalance;
        CardFDBaseInfoLayout lIntegral;


        CardFDInfo cardFDInfo;

        public void set(CardFDInfo c) {
            if (c == null) return;
            cardFDInfo = c;
            notifyDataSetChanged();

            notifyBalanceAndIntegral();
        }

        private void notifyBalanceAndIntegral() {
            if (lBalance != null) {
                String value;
                if (cardFDInfo.balance <= 0) {
                    value = "0.00";
                } else if (cardFDInfo.balance % 1 == 0) {
                    value = String.valueOf((int) cardFDInfo.balance);
                } else {
                    value = String.valueOf(cardFDInfo.balance);
                }
                lBalance.setData("当前余额(元)", value);
            }

            if (lIntegral != null) {
                lIntegral.setData("当前积分", String.valueOf(cardFDInfo.integral));
            }
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            View layout = container.findViewWithTag("courseInfo#" + position);
            if (layout != null) {
                container.removeView(layout);
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View layout = null;
            if (position == 0) {
                CardFDBaseInfoLayout item = new CardFDBaseInfoLayout(container.getContext());
                lBalance = item;

                String value;
                if (cardFDInfo.balance <= 0) {
                    value = "0.00";
                } else if (cardFDInfo.balance % 1 == 0) {
                    value = String.valueOf((int) cardFDInfo.balance);
                } else {
                    value = String.valueOf(cardFDInfo.balance);
                }
                item.setData("当前余额(元)", value);
                layout = item;
            } else if (position == 1) {
                CardFDBaseInfoLayout item = new CardFDBaseInfoLayout(container.getContext());
                lIntegral = item;

                item.setData("当前积分", String.valueOf(cardFDInfo.integral));
                layout = item;
            } else {
                CardFDCourseInfoLayout item = new CardFDCourseInfoLayout(container.getContext());
                item.setData(cardFDInfo.orderList.get(position - 2));
                layout = item;
            }
            layout.setTag("courseInfo#" + position);
            container.addView(layout);
            return layout;
        }

        @Override
        public int getCount() {
            if (cardFDInfo == null) return 0;
            int courseCount = cardFDInfo.orderList != null ? cardFDInfo.orderList.size() : 0;
            return 2 + courseCount;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    static class RecordAdapter extends RecyclerView.Adapter {
        final List<CardFDInfo.OrderFinance> orderFinanceList = new ArrayList<>();

        public void set(CardFDInfo cardFDInfo) {
            orderFinanceList.clear();
            if (cardFDInfo.orderFinanceList != null) {
                orderFinanceList.addAll(cardFDInfo.orderFinanceList);
            }
            notifyDataSetChanged();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            ImageView iLogo;
            TextView tTitle, tContent, tTime1, tTime2;
            View lContent;

            CardFDInfo.OrderFinance of;

            ViewHolder(View itemView) {
                super(itemView);
                iLogo = (ImageView) itemView.findViewById(R.id.i_logo);
                tTitle = (TextView) itemView.findViewById(R.id.t_title);
                tContent = (TextView) itemView.findViewById(R.id.t_content);
                tTime1 = (TextView) itemView.findViewById(R.id.t_time_1);
                tTime2 = (TextView) itemView.findViewById(R.id.t_time_2);
                lContent = itemView.findViewById(R.id.l_content);
            }

            void refresh(CardFDInfo.OrderFinance data) {
                if (data == null) {
                    itemView.setVisibility(View.GONE);
                } else {
                    itemView.setVisibility(View.VISIBLE);
                    of = data;
                    if (of.status == CardFDInfo.OrderFinance.STATUS_CONSUME_GOODS_COUNT) {
                        // 1消费商品次数
                        iLogo.setImageResource(R.mipmap.card_fd_record_1);
                        tContent.setText(of.changeNum + "次");
                        tTitle.setText("消费-" + of.productName);
                    } else if (of.status == CardFDInfo.OrderFinance.STATUS_RECHARGE_GOODS_COUNT) {
                        //2充值商品次数
                        iLogo.setImageResource(R.mipmap.card_fd_record_2);
                        tContent.setText(of.changeNum + "次");
                        tTitle.setText("充值次数-" + of.productName);
                    } else if (of.status == CardFDInfo.OrderFinance.STATUS_RECHARGE_BALANCE) {
                        // 3充值余额
                        iLogo.setImageResource(R.mipmap.card_fd_record_3);
                        tContent.setText("￥" + formatNumber(of.changeMoney));
                        tTitle.setText("账户充值");
                    } else if (of.status == CardFDInfo.OrderFinance.STATUS_CONSUME_BALANCE) {
                        //  4消费余额
                        iLogo.setImageResource(R.mipmap.card_fd_record_4);
                        tContent.setText("￥" + formatNumber(of.useBalanceMoney));
                        tTitle.setText("消费余额");
                    } else if (of.status == CardFDInfo.OrderFinance.STATUS_BALANCE_REFUND) {
                        // 5余额退款
                        iLogo.setImageResource(R.mipmap.card_fd_record_5);
                        tContent.setText("￥" + formatNumber(of.changeMoney));
                        tTitle.setText("余额退款");
                    } else if (of.status == CardFDInfo.OrderFinance.STATUS_GOODS_REFUND) {
                        // 6商品退款
                        iLogo.setImageResource(R.mipmap.card_fd_record_6);
                        tContent.setText("￥" + formatNumber(of.actualMoney));
                        tTitle.setText("商品退款-" + of.productName);
                    } else if (of.status == CardFDInfo.OrderFinance.STATUS_BUY) {
                        // 7购买
                        iLogo.setImageResource(R.mipmap.card_fd_record_7);
                        tContent.setText("￥" + formatNumber(of.buyPrice));
                        tTitle.setText("购买-" + of.productName);
                    }
                    String[] time = formatRecordTime(of.createTime);
                    tTime1.setText(time[0]);
                    tTime2.setText(time[1]);
                }
            }

            private String formatNumber(float value) {
                if (value == 0) return "0";
                if (value % 1 == 0) {
                    return String.valueOf((int) value);
                } else {
                    return String.valueOf(value);
                }
            }
        }

        SimpleDateFormat format = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
        Calendar today = Calendar.getInstance();
        Calendar yesterday = Calendar.getInstance();

        String[] formatRecordTime(long timestamp) {
            String[] timeInfo = new String[2];
            String sTimestamp = String.valueOf(timestamp);
            if (sTimestamp.length() != 14) return timeInfo;
            try {
                Date date = format.parse(sTimestamp);
                Calendar current = Calendar.getInstance();
                today.set(Calendar.YEAR, current.get(Calendar.YEAR));
                today.set(Calendar.MONTH, current.get(Calendar.MONTH));
                today.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH));
                //  Calendar.HOUR——12小时制的小时数 Calendar.HOUR_OF_DAY——24小时制的小时数
                today.set(Calendar.HOUR_OF_DAY, 0);
                today.set(Calendar.MINUTE, 0);
                today.set(Calendar.SECOND, 0);

                yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));
                yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));
                yesterday.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) - 1);
                yesterday.set(Calendar.HOUR_OF_DAY, 0);
                yesterday.set(Calendar.MINUTE, 0);
                yesterday.set(Calendar.SECOND, 0);

                timeInfo[1] = sTimestamp.substring(8, 10) + ":" + sTimestamp.substring(10, 12);
                current.setTime(date);
                if (current.after(today)) {
                    timeInfo[0] = "今天";
                } else if (current.before(today) && current.after(yesterday)) {
                    timeInfo[0] = "昨天";
                } else {
                    timeInfo[0] = sTimestamp.substring(4, 6) + "-" + sTimestamp.substring(6, 8);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                return timeInfo;
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_card_fd_course_info, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ViewHolder vh = (ViewHolder) holder;
            vh.refresh(orderFinanceList.get(position));
        }

        @Override
        public int getItemCount() {
            return orderFinanceList.size();
        }
    }
}
